package com.xiaogao.serviceEdu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaogao.serviceBase.utils.exceptionHandler.XiaoGaoException;
import com.xiaogao.serviceEdu.entity.EduSubject;
import com.xiaogao.serviceEdu.entity.excel.SubjectData;
import com.xiaogao.serviceEdu.service.EduSubjectService;

/**
 * @author 小高
 * @createtime 2021-06-06-22:43
 * @description excel监听器
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    // 因为SubjectExcelListener不能交给Spring进行管理，需要自己new，不能注入其他对象
    // 也不能实现操作数据库操作
    public EduSubjectService subjectService;

    public SubjectExcelListener() {}
    // 创建有参构造函数，传递subjectService用于操作数据库
    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    // 一行一行读取excel内容
    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if(data == null){
            throw new XiaoGaoException(20001,"文件数据为空");
        }

        // 一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        // 添加一级分类
        EduSubject oneSubject = this.existOneSubject(subjectService, data.getOneSubjectName());
        if(oneSubject == null){ // 没有相同的一级分类
            oneSubject = new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(data.getOneSubjectName()); // 一级分类名称
            subjectService.save(oneSubject);
        }

        // 获取一级分类id值
        String pid = oneSubject.getId();
        // 添加二级分类
        EduSubject twoSubject = this.existTwoSubject(subjectService, data.getTwoSubjectName(),pid);
        if(twoSubject == null){
            twoSubject = new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(data.getTwoSubjectName()); // 二级分类名称
            subjectService.save(twoSubject);
        }

    }

    // 判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        // select * from edu_subject where title=? and parent_id=?
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    // 判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    // 读取完成后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
